<template>
  <div class="login">
    <div class="login-box">
      <div class="box-right">
        <div class="top">
          <img src="../../../public/img/login/logo.png" alt="">直路外贸管理平台
        </div>
        <el-form :model="form" :rules="rules" ref="ruleForm" label-width="70px"
                 @keyup.enter.native="submit">
          <el-form-item label="企业ID" prop="tenantId">
            <el-input type="text" size="small" v-model="form.tenantId" placeholder="请输入企业ID"
                      autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="账 号" prop="username">
            <el-input type="text" size="small" v-model="form.username" placeholder="请输入登录账号"
                      autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密 码" prop="password" class="password">
            <el-input :type="!state?'password':'text'" size="small" v-model="form.password" placeholder="请输入登录密码"
                      autocomplete="off"></el-input>
            <i :class="state?'el-icon-view':'icon-yanjing'"
               :style="{top:state?'28%':'5%'}"
               @click="state=!state"></i>
          </el-form-item>
          <div class="footer">
            <el-button type="primary" @click="submit" :loading="loading">{{loading?'登录中...':'登 录'}}</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
    import {queryMessageList} from '@/api/message'
    import {loginByUsername} from '@/api/user'
    import {popNotice} from "@/util/util"
    import {mapState} from 'vuex'
    export default {
        name: "login",
        data() {
            return {
                form: {
                    tenantId: localStorage.getItem("zhiluTenantId"),
                    username: '',
                    password: '',
                    type: "account"
                },
                rules: {
                    tenantId:[
                        {required: true, message: '请输入企业ID', trigger: 'blur'},
                    ],
                    username: [
                        {required: true, message: '请输入登录账号', trigger: 'blur'},
                    ],
                    password: [
                        {required: true, message: '请输入登录密码', trigger: 'blur'}
                    ],
                },
                state: false,
                loading:false
            }
        },
        computed:{
          ...mapState(['common'])
        },
        created(){
            this.clearCookie();//清空cookie
            if(this.common.isExpired){//过期导致
                this.$message({
                    showClose: true,
                    message: '登录已过期，请重新登录!',
                    type: "success"
                });
                this.$store.commit('set_isExpire',false);
            }
            console.log(this.common)
            console.log("%c -----------------  welcome to zhiLu 欢迎加入直路外贸云平台 ^_^ ------------------","color:#2a97f9")
        },
        methods: {
            submit() {
                this.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        this.loading=true;
                        loginByUsername(this.form.tenantId, this.form.username, this.form.password, this.form.type).then(res => {
                            this.loading=false;
                            if (res.data.access_token) {
                                localStorage.setItem("zhiluTenantId", this.form.tenantId);
                                this.$store.commit('SET_TOKEN', res.data.refresh_token);
                                this.$store.commit('SET_USER_INFO', res.data);
                                this.$store.dispatch('GetMenu', '');
                                this.$router.push('/home');
                                this.$store.dispatch('set_message');
                                this.$store.dispatch('get_country');
                                // 获取客户通用信息
                                this.$store.dispatch('get_customer');

                                // 请求消息
                                queryMessageList(1, 5, '', 4, false).then(res => {
                                    var list = res.data.data
                                    if (list.length > 0) {
                                        list.forEach(value => {
                                            if(window.Notification) {
                                                if (Notification.permission == "granted") {
                                                    popNotice(value);
                                                } else if (Notification.permission != "denied") {
                                                    Notification.requestPermission(function (permission) {
                                                        popNotice(value);
                                                    });
                                                }
                                            }
                                        })
                                    }
                                })
                                return;
                            } else {
                                let message = ''
                                switch (res.data.error_description) {
                                    case "AccountExpired":
                                        message = '该账号已过期，请联系客服'
                                        break
                                    default:
                                        message = '账号密码错误'
                                        break
                                }
                                this.$message({
                                    showClose: true,
                                    message: message,
                                    type: 'error'
                                })
                            }
                        }).catch(err => {
                            this.loading=false;
                        });
                    } else {
                        return false;
                    }
                });
            },
            clearCookie(){
                let keys=document.cookie.match(/[^ =;]+(?=\=)/g);
                if (keys) {
                    for (var i = keys.length; i--;)
                        document.cookie=keys[i]+'=0;expires=' + new Date( 0).toUTCString()
                }
            }
        }
    };
</script>

<style lang="scss">
  @import "@/styles/login.scss";

  .login {
    background: url("../../../public/img/login/login-bg.png") no-repeat;
    background-size: 100% 100%;
    .el-form-item.password{
      i{
        right: 4%;
      }
    }
  }
</style>
